<template>
  <div class="python-model">
    <div class="search-section">
      <a-row :gutter="16">
        <a-col :span="4">
          <a-input v-model="searchForm.tagName" placeholder="输入模型标签" allowClear />
        </a-col>
        <a-col :span="4">
          <a-input v-model="searchForm.modelUuid" placeholder="输入模型编号" allowClear />
        </a-col>
        <a-col :span="4">
          <a-input v-model="searchForm.name" placeholder="输入模型名称" allowClear />
        </a-col>
        <a-col :span="4">
          <a-button type="primary" @click="handleSearch"> 搜索 </a-button>
        </a-col>
        <a-col :span="8" style="text-align: right">
          <a-button type="primary" @click="uploadPythonModel"> {{ uploadModelButtonText }} </a-button>
        </a-col>
      </a-row>
    </div>

    <div class="table-section">
      <s-table
        :loading="loading"
        :expanded-row-keys="expandedRowKeys"
        @expand="onExpand"
        @expandedRowsChange="onExpandedRowsChange"
        expandRowByClick
        row-key="id"
        size="middle"
        ref="table"
        :columns="columns"
        :data="loadData"
        :alert="false"
        showPagination="auto"
      >
        <template slot="modelName" slot-scope="text, record">
          <a-tooltip :title="`${record.name} 【${record.uuid}】`">
            <span>{{ `${record.name} 【${record.uuid}】` }}</span>
          </a-tooltip>
        </template>
        <!-- 操作列自定义渲染 -->
        <template slot="action" slot-scope="text, record">
          <a-button type="link" @click.stop="handleVersionUpdate(record)"> 版本更新 </a-button>
          <a-divider type="vertical" />
          <a-button type="link" @click.stop="handlePermissionManage(record)" v-if="record.isOwner"> 权限管理 </a-button>
          <a-tooltip title="您不是当前模型的负责人，无权访问该功能" placement="top" v-else>
            <a-button type="link" disabled @click="(e) => e.preventDefault()">权限管理</a-button>
          </a-tooltip>
        </template>

        <!-- 展开行内容 - 正确的使用方式 -->
        <template slot="expandedRowRender" slot-scope="record">
          <a-table
            :columns="detailColumns"
            :data-source="record.detailData"
            :pagination="false"
            size="small"
            :show-header="false"
            :customRow="customRow"
            row-key="id"
            v-if="record.detailData && record.detailData.length"
          >
            <!-- 子表操作列 -->
            <!-- 状态列自定义渲染 -->
            <template slot="modelName" slot-scope="text, detailRecord">
              {{ `${detailRecord.name} ${detailRecord.version}` }}
              <a-tag v-if="detailRecord.tags" closable @close="handleDeleteTag(record, detailRecord)" color="blue">{{
                detailRecord.tags
              }}</a-tag>
              <template v-else>
                <a-icon type="plus-square" @click.stop="isShowInput = true" v-if="!isShowInput" />
                <a-input
                  v-if="isShowInput"
                  v-model="tagStr"
                  @keydown.enter="handleAddTag(record, detailRecord)"
                  @input="onChange"
                  @click.stop
                  style="width: 100px; display: inline-block; height: 24px"
                  :maxLength="8"
                />
              </template>
            </template>
            <template slot="status" slot-scope="text, detailRecord">
              <a-popover
                v-if="isNeedAudit"
                title="审核进度"
                @visibleChange="(visible) => handleVisibleChange(detailRecord, visible)"
              >
                <template slot="content">
                  <a-steps :current="auditStatus" size="small">
                    <a-step v-for="process in processFlowList" :title="process.title" :key="process.id">
                      <template slot="description">
                        <span style="font-size: 12px"><a-icon type="user" />{{ process.name }}</span>
                        <br />
                        <span style="font-size: 12px">{{ process.time }}</span>
                      </template>
                    </a-step>
                  </a-steps>
                </template>
                <a-badge :status="text ? 'success' : 'error'" :text="text | formatText" />
              </a-popover>
              <span v-else>{{ text | formatText }}</span>
            </template>
            <template slot="action" slot-scope="text, detailRecord">
              <a-tooltip
                title="'测试'成功后才可以上线"
                v-if="
                  !detailRecord.enabled &&
                    detailRecord.processStatus &&
                    ['0', '7', '9'].includes(detailRecord.processStatus)
                "
              >
                <a-button type="link" disabled> 上线 </a-button>
              </a-tooltip>
              <a-button type="link" @click.stop="handleDisable(detailRecord)" v-else>
                {{ detailRecord.enabled ? '下线' : '上线' }}
              </a-button>
              <a-divider type="vertical" />
              <a-dropdown>
                <a class="ant-dropdown-link" @click.stop="(e) => e.preventDefault()">监控<a-icon type="down" /> </a>
                <a-menu slot="overlay">
                  <a-menu-item @click="handleViewMonitorResult(detailRecord)" :disabled="!detailRecord.monitor">
                    <a-tooltip title="尚未配置监控" v-if="!detailRecord.monitor" placement="topRight">
                      查看结果
                    </a-tooltip>
                    <span v-else>查看结果</span>
                  </a-menu-item>
                  <a-menu-item @click="handleViewMonitorConfig(detailRecord)"> 监控配置 </a-menu-item>
                </a-menu>
              </a-dropdown>
              <a-divider type="vertical" />
              <a-dropdown>
                <a class="ant-dropdown-link" @click.stop="(e) => e.preventDefault()">预警<a-icon type="down" /> </a>
                <a-menu slot="overlay">
                  <a-menu-item
                    @click="handleViewWarningEvent(detailRecord)"
                    :disabled="!detailRecord.monitor || !detailRecord.alert"
                  >
                    <a-tooltip
                      :title="
                        !detailRecord.monitor ? '尚未配置监控，请先配置监控' : !detailRecord.alert ? '尚未配置预警' : ''
                      "
                      v-if="!detailRecord.monitor || !detailRecord.alert"
                      placement="topRight"
                    >
                      预警事件
                    </a-tooltip>
                    <span v-else>预警事件</span>
                  </a-menu-item>
                  <a-menu-item @click="handleViewWarningConfig(detailRecord)" :disabled="!detailRecord.monitor">
                    <a-tooltip title="尚未配置监控，请先配置监控" v-if="!detailRecord.monitor" placement="topRight">
                      预警配置
                    </a-tooltip>
                    <span v-else>预警配置</span>
                  </a-menu-item>
                </a-menu>
              </a-dropdown>
              <a-divider type="vertical" />
              <a-dropdown>
                <a class="ant-dropdown-link" @click.stop="(e) => e.preventDefault()">更多<a-icon type="down" /> </a>
                <a-menu slot="overlay">
                  <a-menu-item @click="handleRowClick(detailRecord)"> 详情 </a-menu-item>
                  <a-menu-item @click="handleTest(detailRecord)"> 测试 </a-menu-item>
                  <a-menu-item @click="handleDelete(detailRecord)" :disabled="!record.isOwner">
                    <a-tooltip
                      title="您不是当前模型的负责人，无权访问该功能"
                      v-if="!record.isOwner"
                      placement="topRight"
                    >
                      删除
                    </a-tooltip>
                    <span v-else>删除</span>
                  </a-menu-item>
                  <a-menu-item v-if="modelType === 'python'" @click="handleBatchTesting(detailRecord)">
                    批量测试
                  </a-menu-item>
                  <a-menu-item @click="handleDownloadDoc(detailRecord)"> 下载文档 </a-menu-item>
                  <a-menu-item @click="handleDownloadModel(detailRecord)"> 下载模型 </a-menu-item>
                </a-menu>
              </a-dropdown>
            </template>
          </a-table>
          <div class="skeleton" v-else>
            <a-spin />
          </div>
        </template>
      </s-table>
    </div>
    <!-- 模型详情弹窗 -->
    <a-drawer
      :title="modelDetail.title"
      :visible.sync="drawerVisible"
      destroyOnClose
      width="70%"
      :footer="null"
      @close="onDrawerClose"
      :getContainer="$drawerConfig.getContainer"
    >
      <ScoreModelDetail
        v-if="modelType === 'scorecard'"
        :currentDetailRecord="modelDetail.data"
        :modelType="modelType"
      />
      <ModelDetail v-else :currentDetailRecord="modelDetail.data" :modelType="modelType" />
    </a-drawer>
    <!-- 编辑与创建弹窗 -->
    <a-modal
      :visible.sync="editAddModalVisible"
      :title="uploadModelButtonText"
      :width="modelType === 'python' ? '80%' : '40%'"
      :destroyOnClose="true"
      :footer="null"
      @cancel="handleClose"
    >
      <EditAndAddForm
        :initialData="editData"
        :isEdit="isEdit"
        @updateList="updateList"
        @cancel="handleClose"
        v-if="modelType === 'python'"
      />
      <EditAndCreateModel
        v-else-if="modelType === 'pmml'"
        :initialData="editData"
        :isEdit="isEdit"
        @updateList="updateList"
        @cancel="handleClose"
      />
      <EditAndCreateScoreModel
        v-else-if="modelType === 'scorecard'"
        :initialData="editData"
        :isEdit="isEdit"
        @updateList="updateList"
        @cancel="handleClose"
      />
    </a-modal>
    <!-- 权限管理弹窗 -->
    <a-drawer
      title="模型权限管理 / 配置模型管理信息"
      placement="right"
      closable
      :visible="permissionDrawerVisible"
      @close="permissionDrawerVisible = false"
      destroyOnClose
      width="500px"
      :getContainer="$drawerConfig.getContainer"
    >
      <PermissionManage :modelData="currentDetailRecord" @updateList="updateList" />
    </a-drawer>
    <!-- 监控配置弹窗 -->
    <a-drawer
      title="监控配置"
      placement="left"
      closable
      :visible="monitorDrawerVisible"
      destroyOnClose
      @close="monitorDrawerVisible = false"
      width="80%"
      :getContainer="$drawerConfig.getContainer"
    >
      <MonitorConfig :modelData="currentDetailRecord" @updateList="updateList" @close="monitorDrawerVisible = false" />
    </a-drawer>
    <!-- 预警配置弹窗 -->
    <WarnConfigure
      :visible="warnConfigureVisible"
      :record="currentDetailRecord"
      @close="handleWarnConfigureClose"
      @confirm="handleWarnConfigureConfirm"
    />
    <!-- 批量测试弹窗 -->
    <a-drawer
      title="上传模型测试文件"
      placement="right"
      closable
      :visible="batchTestingDrawerVisible"
      @close="batchTestingDrawerVisible = false"
      destroyOnClose
      width="40%"
      :getContainer="$drawerConfig.getContainer"
    >
      <PythonBatchTesting :currentDetailRecord="currentDetailRecord" />
    </a-drawer>
    <!-- 测试弹窗 -->
    <TestPop
      :visible="testVisible"
      :model-data="currentTestModel"
      :model-type="modelType"
      :model-api="modelAPI"
      @close="handleTestClose"
      @test-complete="handleTestComplete"
    />
    <!-- 审核弹窗 -->
    <a-modal
      title="提交审核申请"
      closable
      :visible="auditDrawerVisible"
      destroyOnClose
      width="500px"
      @ok="handleAuditSubmit"
      @cancel="handleAuditCancel"
    >
      <AuditModel
        ref="auditModel"
        :currentDetailRecord="currentDetailRecord"
        :applyType="applyType"
        @updateList="updateList"
      />
    </a-modal>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { Codemirror } from 'vue-codemirror'
import { STable } from '@/components'
import { deleteTag, addTag, invokePDF, getSimpleSystemConfig, processFlow } from '@/api/manage'
import moment from 'moment'
import ModelDetail from './ModelDetail'
import ScoreModelDetail from './ScoreModelDetail'
import EditAndAddForm from './EditAndAddForm'
import PermissionManage from './PermissionManage'
import MonitorConfig from './MonitorConfig'
import WarnConfigure from '@/components/WarnConfigure'
import { createModelAPI } from '@/api/modelAdapter'
import EditAndCreateModel from './EditAndCreateModel'
import EditAndCreateScoreModel from './EditAndCreateScoreModel'
import PythonBatchTesting from './PythonBatchTesting'
import TestPop from '@/components/TestPop'
import AuditModel from './AuditModel'
import { approvalTypeMap } from './config'

export default {
  name: 'PythonModel',
  components: {
    Codemirror,
    STable,
    ModelDetail,
    ScoreModelDetail,
    EditAndAddForm,
    PermissionManage,
    MonitorConfig,
    WarnConfigure,
    EditAndCreateModel,
    EditAndCreateScoreModel,
    PythonBatchTesting,
    TestPop,
    AuditModel,
  },
  props: {
    modelType: {
      type: String,
      default: 'python',
    },
  },
  filters: {
    formatText(text) {
      return text ? '已上线' : '已下线'
    },
  },
  data() {
    return {
      loading: false,
      searchForm: {
        modelUuid: '',
        tagName: '',
        name: '',
      },
      expandedRowKeys: [],
      // 弹窗相关
      detailModalVisible: false,
      currentDetailRecord: {},
      modelCode: '',
      pagination: {
        current: 1,
        pageSize: 10,
      },
      tagStr: '',
      // 主表列定义
      columns: [
        {
          title: '模型名称',
          dataIndex: 'name',
          key: 'name',
          width: 200,
          ellipsis: true,
          scopedSlots: { customRender: 'modelName' },
        },
        {
          title: '上传人员',
          dataIndex: 'createdBy',
          key: 'createdBy',
          width: 100,
        },
        {
          title: '状态',
          dataIndex: 'statusCode',
          key: 'statusCode',
          width: 100,
          customRender: (text, record) => {
            return ''
          },
        },
        {
          title: '执行时间',
          dataIndex: 'gmtCreate',
          key: 'gmtCreate',
          width: 200,
          customRender: (text, record) => {
            return ''
          },
        },
        {
          title: '操作',
          key: 'action',
          width: 200,
          scopedSlots: { customRender: 'action' },
        },
      ],
      // 子表列定义
      detailColumns: [
        {
          title: '模型名称',
          dataIndex: 'name',
          key: 'name',
          //   customRender: (text, record) => {
          //     return `${record.name} ${record.version}`
          //   },
          scopedSlots: { customRender: 'modelName' },
          width: 200,
        },
        {
          title: '上传人员',
          dataIndex: 'modifiedBy',
          key: 'modifiedBy',
          width: 100,
        },
        {
          title: '状态',
          dataIndex: 'enabled',
          key: 'enabled',
          scopedSlots: { customRender: 'status' },
          width: 100,
        },
        {
          title: '执行时间',
          dataIndex: 'gmtCreate',
          key: 'gmtCreate',
          customRender: (text, record) => {
            return moment(text).format('YYYY-MM-DD HH:mm:ss')
          },
          width: 200,
        },
        {
          title: '操作',
          key: 'action',
          width: 200,
          scopedSlots: { customRender: 'action' },
        },
      ],
      isShowInput: false,
      detailData: [],
      drawerVisible: false,
      selectedDetailRecord: null,
      editAddModalVisible: false,
      editData: null,
      isEdit: false,
      requestParams: {},
      permissionDrawerVisible: false,
      monitorDrawerVisible: false,
      warnConfigureVisible: false,
      batchTestingDrawerVisible: false,
      testVisible: false,
      currentTestModel: null,
      configVal: '',
      configKey: '',
      processFlowList: [],
      auditDrawerVisible: false,
      applyType: '',
      modelAPI: null,
    }
  },
  computed: {
    ...mapGetters(['userInfo', 'systemConfig', 'systemConfigKey']),
    modelDetail() {
      const modelTypeMap = {
        python: 'Python模型',
        pmml: 'PMML模型',
        scorecard: '评分卡模型',
      }
      const prefix = modelTypeMap[this.modelType]
      if (!this.selectedDetailRecord) {
        return {
          title: prefix,
          data: {},
        }
      }
      const { name, version } = this.selectedDetailRecord
      return {
        title: `${prefix} - ${name}.${version}详情`,
        data: this.selectedDetailRecord,
      }
    },
    uploadModelButtonText() {
      const textMap = {
        python: '上传Python模型',
        pmml: '上传PMML模型',
        scorecard: '上传评分卡模型',
      }
      return textMap[this.modelType] || '上传模型'
    },
    // 是否需要审核
    isNeedAudit() {
      return this.configVal === '1'
    },
    // 审核当前处于的状态
    auditStatus() {
      if (!this.processFlowList || this.processFlowList.length === 0) {
        return 0
      }
      // index 0:状态未发生 1:状态已经发生 2:当前状态
      return this.processFlowList.findIndex((item) => item.index === '2')
    },
  },
  watch: {
    systemConfig: {
      handler(newVal, oldVal) {
        if (newVal && newVal.length) {
          const key = this.systemConfigKey('3')
          this.configKey = key
          this.getSimpleSystemConfig(key)
        }
      },
      immediate: true,
    },
  },
  created() {
    // 初始化API适配器
    this.modelAPI = createModelAPI(this.modelType)
  },
  methods: {
    getSimpleSystemConfig(key) {
      getSimpleSystemConfig({ key }).then((res) => {
        if (res.data) {
          this.configVal = res.data
        }
      })
    },
    /**
     * 加载主表数据
     */
    loadData(parameter) {
      const requestParameters = Object.assign(
        {},
        {
          curPage: parameter.pageNo,
          pageSize: parameter.pageSize,
        },
        this.searchForm
      )
      this.loading = true
      console.log('loadData request parameters:', requestParameters)
      // 存储请求参数,刷新的时候重新调用
      this.requestParams = requestParameters
      this.expandedRowKeys = []
      return this.modelAPI.getModelList(requestParameters).then((res) => {
        const { modelData, list } = res.data
        this.loading = false
        if (modelData || list) {
          res.data.data = (modelData || list).map((item) => {
            item.isOwner = item.createdBy === this.userInfo.userName
            return item
          })
          delete res.data.modelData
          delete res.data.list
        }
        if (!res.data.curPage) {
          res.data.curPage = parameter.pageNo
        }
        if (!res.data.pageSize) {
          res.data.pageSize = parameter.pageSize
        }
        return res.data
      })
    },
    /**
     * 加载子表数据
     */
    loadDetailData(record) {
      const { current, pageSize } = this.pagination
      const requestParameters = {
        curPage: current,
        pageSize,
        modelUuid: record.uuid,
      }
      this.modelAPI.getModelVersionInfo(requestParameters).then((res) => {
        const { datas } = res.data
        console.log('datas', datas)
        if (datas.length) {
          // 设置表格数据触发更新
          this.$set(record, 'detailData', datas)
        }
      })
    },
    updateList() {
      this.editAddModalVisible = false
      this.permissionDrawerVisible = false
      this.handleSearch()
    },
    /**
     * 搜索
     */
    handleSearch() {
      // 搜索逻辑已在computed中处理
      this.$refs.table.refresh(true)
    },
    /**
     * 版本更新
     */
    handleVersionUpdate(record) {
      // 权限映射表
      const permissionMap = {
        scorecard: 'updateScoreCardModel',
        python: 'updatePythonModel',
        pmml: 'updatePmmlModel',
      }

      // 检查对应模型类型的权限
      const permission = permissionMap[this.modelType]
      if (permission && !this.$hasPermission(permission)) {
        this.$message.error('您没有权限更新模型')
        return
      }
      this.editAddModalVisible = true
      const editData = this.modelType === 'python' ? JSON.parse(record.configJson) : record
      this.editData = editData
      this.isEdit = true
    },
    /**
     * 关闭弹窗
     */
    handleClose() {
      this.editAddModalVisible = false
      this.editAddModalVisible = false
      this.editData = null
      this.isEdit = false
    },
    /**
     * 权限管理
     */
    handlePermissionManage(record) {
      console.log('权限管理', record)
      this.permissionDrawerVisible = true
      this.currentDetailRecord = Object.assign({}, record)
    },
    /**
     * 删除标签
     */
    handleDeleteTag(record, detailRecord) {
      if (!this.$hasPermission('deleteModelTag')) {
        this.$message.error('您没有权限删除标签')
        return
      }
      const params = {
        modelUuid: detailRecord.uuid,
        tagName: detailRecord.tags,
        version: detailRecord.version,
      }
      deleteTag(params).then((res) => {
        if (res.code === 200) {
          this.$message.success('删除成功')
          this.loadDetailData(record)
        }
      })
    },
    /**
     * 下线模型
     */
    async handleDisable(record) {
      // 权限映射表
      const permissionMap = {
        scorecard: 'scoreCardModelOnlineOffline',
        python: 'pythonModelOnlineOffline',
        pmml: 'pmmlModelOnlineOffline',
      }
      // 检查对应模型类型的权限
      const permission = permissionMap[this.modelType]
      if (permission && !this.$hasPermission(permission)) {
        this.$message.error('您没有权限下线模型')
        return
      }
      try {
        const res = await getSimpleSystemConfig({ key: this.configKey })
        if (res.data === '1') {
          // 需要审核展示审核界面
          this.auditDrawerVisible = true
          this.applyType = approvalTypeMap[record.enabled ? 'offline' : 'online'][this.modelType]
          this.currentDetailRecord = record
          return
        }
      } catch (error) {
        this.$message.error('获取系统配置失败')
        return
      }
      const handleDisable = (enabled) => {
        this.modelAPI
          .setModelStatus({
            modelUuid: record.uuid,
            version: record.version,
            enabled,
          })
          .then((res) => {
            if (res.code === 200) {
              this.$message.success(res.message)
              this.handleSearch()
            } else {
              this.$message.error(res.message)
            }
          })
      }
      if (record.enabled) {
        this.$confirm({
          title: '下线提醒!',
          content: (h) => <div>{`您真的要下线版本"${record.version}"吗？`}</div>,
          onOk() {
            handleDisable(false)
          },
          onCancel() {
            console.log('Cancel')
          },
          class: 'test',
        })
        return
      }
      handleDisable(true)
    },
    /**
     * 查看监控结果
     */
    handleViewMonitorResult(record) {
      this.$router.push({
        path: '/model/monitorResult',
        query: {
          modelUuid: record.uuid,
          version: record.version,
        },
      })
    },
    /**
     * 查看监控配置
     */
    handleViewMonitorConfig(record) {
      this.monitorDrawerVisible = true
      this.currentDetailRecord = record
      console.log('查看监控配置', record)
    },
    /**
     * 查看预警事件
     */
    handleViewWarningEvent(record) {
      this.$router.push({
        path: '/model/warningEvent',
        query: {
          modelUuid: record.uuid,
          version: record.version,
        },
      })
    },
    /**
     * 查看预警配置
     */
    handleViewWarningConfig(record) {
      this.warnConfigureVisible = true
      this.currentDetailRecord = record
      console.log('查看预警配置', record)
    },
    /**
     * 关闭预警配置弹窗
     */
    handleWarnConfigureClose() {
      this.warnConfigureVisible = false
      this.currentDetailRecord = {}
    },
    /**
     * 预警配置确认
     */
    handleWarnConfigureConfirm(data) {
      console.log('预警配置数据:', data)
      this.$message.success('预警配置保存成功')
      this.warnConfigureVisible = false
    },
    onChange() {
      // 校验特殊字符及长度不能超过8为字符并格式化输入
      if (this.tagStr.length > 8) {
        this.$message.error('长度不能超过8个字符')
        return
      }
      if (/[^\w\u4e00-\u9fa5]/.test(this.tagStr)) {
        this.$message.error('只能包含字母、数字、中文和下划线')
        return
      }
      // 去除无效字符
      this.tagStr = this.tagStr.replace(/[^\w\u4e00-\u9fa5]/g, '')
    },
    handleAddTag(record, detailRecord) {
      if (!this.$hasPermission('addModelTag')) {
        this.$message.error('您没有权限添加标签')
        return
      }
      const params = {
        modelUuid: detailRecord.uuid,
        tagName: this.tagStr,
        version: detailRecord.version,
      }
      addTag(params).then((res) => {
        if (res.code === 200) {
          this.isShowInput = false
          this.$message.success('添加成功')
          this.tagStr = ''
          this.loadDetailData(record)
        }
      })
    },
    handleVisibleChange(record, visible) {
      if (!visible) {
        this.processFlowList = []
        return
      }
      processFlow({
        modelUuid: record.uuid,
        version: record.version,
      }).then((res) => {
        if (res.code === 200) {
          // status 0:测试中 1:审核成功 2:审核失败 3:上线审核中 4:下线审核中 5:删除审核中 6: 模型测试成功 7: 模型测试失败 8: 上线 9: 下线
          const statusMap = {
            0: '测试中',
            1: '审核成功',
            2: '审核失败',
            3: '上线审核中',
            4: '下线审核中',
            5: '删除审核中',
            6: '模型测试成功',
            7: '测试不通过',
            8: '上线',
            9: '下线',
          }
          this.processFlowList = res.data.map((item, index) => ({
            title: statusMap[item.status],
            ...item,
          }))
        } else {
          this.processFlowList = []
          this.$message.error(res.message)
        }
      })
    },
    uploadPythonModel() {
      // 权限映射表
      const permissionMap = {
        scorecard: 'uploadScoreCardModel',
        python: 'uploadPythonModel',
        pmml: 'uploadPmmlModel',
      }
      // 检查对应模型类型的权限
      const permission = permissionMap[this.modelType]
      if (permission && !this.$hasPermission(permission)) {
        this.$message.error('您没有权限上传模型')
        return
      }
      this.editAddModalVisible = true
      this.editData = null
      this.isEdit = false
    },

    // 自定义行属性，添加点击事件
    customRow(record) {
      return {
        on: {
          click: () => {
            this.handleRowClick(record)
          },
        },
        style: {
          cursor: 'pointer',
        },
      }
    },
    // 处理行点击事件
    handleRowClick(record) {
      // 权限映射表
      const permissionMap = {
        scorecard: 'scoreCardModelDetail',
        python: 'pythonModelDetail',
        pmml: 'pmmlModelDetail',
      }

      // 检查对应模型类型的权限
      const permission = permissionMap[this.modelType]
      if (permission && !this.$hasPermission(permission)) {
        this.$message.error('您没有权限查看模型详情')
        return
      }
      this.selectedDetailRecord = record
      this.drawerVisible = true
    },
    handleTest(record) {
      this.testVisible = true
      this.currentTestModel = {
        modelUuid: record.uuid,
        modelName: record.name,
        version: record.version,
        modelType: record.modelType,
      }
    },
    handleTestClose() {
      this.testVisible = false
      this.currentTestModel = null
    },
    handleTestComplete() {
      this.$message.success('模型测试完成')
      this.handleSearch()
    },
    // 关闭抽屉
    onDrawerClose() {
      this.drawerVisible = false
      this.selectedDetailRecord = null
    },
    onExpand(expanded, record) {
      console.log('展开状态:', expanded, record)
      if (expanded) {
        this.loadDetailData(record)
      }
    },
    onExpandedRowsChange(expandedRows) {
      console.log('onExpandedRowsChange', expandedRows)
      this.expandedRowKeys = expandedRows
    },
    /**
     * 删除模型
     */
    async handleDelete(record) {
      // 权限映射表
      const permissionMap = {
        scorecard: 'deleteScoreCardModel',
        python: 'deletePythonModel',
        pmml: 'deletePmmlModel',
      }
      // 检查对应模型类型的权限
      const permission = permissionMap[this.modelType]
      if (permission && !this.$hasPermission(permission)) {
        this.$message.error('您没有权限删除模型')
        return
      }
      try {
        const res = await getSimpleSystemConfig({ key: this.configKey })
        if (res.data === '1') {
          // 需要审核展示审核界面
          this.auditDrawerVisible = true
          this.applyType = approvalTypeMap.delete[this.modelType]
          this.currentDetailRecord = record
          return
        }
      } catch (error) {
        this.$message.error('获取系统配置失败')
        return
      }
      const _this = this
      this.$confirm({
        title: '删除提醒!',
        content: (h) => <div>{`您真的要删除模型"${record.name}.${record.version}"吗？`}</div>,
        onOk() {
          _this.modelAPI
            .deleteModel({
              modelUuid: record.uuid,
              version: record.version,
            })
            .then((res) => {
              if (res.code === 200) {
                _this.$message.success(res.message)
                _this.handleSearch()
                return
              }
              _this.$message.error(res.message)
            })
        },
        onCancel() {
          console.log('Cancel')
        },
      })
    },
    /**
     * 批量测试
     */
    handleBatchTesting(record) {
      if (!this.$hasPermission('pythonModelTest')) {
        this.$message.error('您没有权限批量测试模型')
        return
      }
      this.batchTestingDrawerVisible = true
      this.currentDetailRecord = record
    },
    /**
     * 下载文档
     */
    handleDownloadDoc(record) {
      invokePDF(
        {
          modelUuid: record.uuid,
          version: record.version,
        },
        {
          defaultFileName: `${record.name}${record.version}Python.pdf`,
        }
      )
    },
    /**
     * 下载模型
     */
    handleDownloadModel(record) {
      // 权限映射表
      const permissionMap = {
        scorecard: 'downloadScoreCardModel',
        python: 'downloadPythonModel',
        pmml: 'downloadModel',
      }
      // 检查对应模型类型的权限
      const permission = permissionMap[this.modelType]
      if (permission && !this.$hasPermission(permission)) {
        this.$message.error('您没有权限下载模型')
        return
      }
      const fileMap = {
        python: `${record.name}${record.version}.zip`,
        pmml: `${record.name}${record.version}.xml`,
        scorecard: `${record.name}${record.version}.xlsx`,
      }
      const fileName = fileMap[this.modelType]
      this.modelAPI.downloadModel(
        {
          modelUuid: record.uuid,
          version: record.version,
        },
        {
          defaultFileName: fileName,
        }
      )
    },
    handleAuditSubmit() {
      this.$refs.auditModel.handleSubmit()
    },
    handleAuditCancel() {
      this.auditDrawerVisible = false
    },
  },
}
</script>

<style lang="less" scoped>
.python-model {
  .search-section {
    background: #fff;
    padding: 16px;
    border-radius: 6px;

    .ant-input {
      height: 32px;
    }

    .ant-btn {
      height: 32px;
    }
  }

  .table-section {
    background: #fff;
    padding: 16px;
    border-radius: 6px;

    .ant-table {
      .ant-table-thead > tr > th {
        background: #fafafa;
        border-bottom: 1px solid #f0f0f0;
        padding: 12px 16px;
        font-weight: 500;
        color: #262626;
      }

      .ant-table-tbody > tr > td {
        padding: 12px 16px;
        border-bottom: 1px solid #f0f0f0;
      }

      .ant-table-row:hover {
        background-color: #f5f5f5;
      }

      .ant-table-expanded-row {
        background-color: #fafafa;

        .ant-table-tbody > tr > td {
          padding: 8px 16px;
          background: transparent;
        }
      }
    }

    .ant-tag {
      margin: 0;
      padding: 2px 8px;
      border-radius: 4px;
      font-size: 12px;
    }

    .ant-btn-link {
      padding: 0;
      height: auto;
      font-size: 14px;

      &:hover {
        color: #40a9ff;
      }
    }

    .ant-divider-vertical {
      margin: 0 8px;
      height: 14px;
    }
    .skeleton {
      text-align: center;
      margin-bottom: 20px;
      margin: 20px 0;
    }
  }

  .pagination-info {
    text-align: center;
    margin-top: 16px;
    color: #8c8c8c;
    font-size: 14px;
  }
}

// 全局样式调整
.ant-table-expand-icon-th,
.ant-table-row-expand-icon-cell {
  width: 50px;
  min-width: 50px;
}

.ant-table-expand-icon {
  color: #1890ff;
  cursor: pointer;

  &:hover {
    color: #40a9ff;
  }
}

// 弹窗样式
.detail-modal-content {
  .detail-info {
    margin-bottom: 24px;

    .ant-descriptions {
      .ant-descriptions-item-label {
        font-weight: 500;
        color: #262626;
        background-color: #fafafa;
      }

      .ant-descriptions-item-content {
        color: #595959;
      }
    }
  }

  .code-editor-section {
    h3 {
      margin-bottom: 16px;
      font-size: 16px;
      font-weight: 500;
      color: #262626;
    }

    .code-editor {
      border: 1px solid #d9d9d9;
      border-radius: 6px;
      overflow: hidden;

      .CodeMirror {
        height: 400px;
        font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
        font-size: 14px;
        line-height: 1.5;
      }

      .CodeMirror-scroll {
        min-height: 400px;
      }

      .CodeMirror-gutters {
        border-right: 1px solid #e8e8e8;
        background-color: #fafafa;
      }

      .CodeMirror-linenumber {
        color: #999;
        padding: 0 8px;
      }

      .CodeMirror-activeline-background {
        background-color: rgba(24, 144, 255, 0.1);
      }

      .CodeMirror-focused .CodeMirror-selected {
        background-color: rgba(24, 144, 255, 0.2);
      }
    }
  }
}

.drawer-actions {
  margin: 16px 0;

  h3 {
    margin-bottom: 12px;
  }
}

.monitoring-section {
  h3 {
    margin-bottom: 12px;
  }
}

.drawer-footer {
  position: absolute;
  right: 0;
  bottom: 0;
  width: 100%;
  border-top: 1px solid #e9e9e9;
  padding: 10px 16px;
  background: #fff;
  text-align: right;
  z-index: 1;
}

// 子表格行悬停效果
/deep/ .ant-table-tbody > tr:hover {
  background-color: #e6f7ff;
  cursor: pointer;
}

// a-drawer 样式设置 - 超出内容滚动
/deep/ .ant-drawer-body {
  height: calc(100vh - 108px); // 减去头部和可能的底部空间
  overflow-y: auto;
  overflow-x: hidden;
  padding: 24px;
}

// a-modal 样式设置 - 超出内容滚动
/deep/ .ant-modal {
  max-height: 90vh;
}

/deep/ .ant-modal-body {
  max-height: calc(90vh - 108px); // 减去头部和底部空间
  overflow-y: auto;
  overflow-x: hidden;
  padding: 24px;
}

// 确保modal内容不会超出视窗
/deep/ .ant-modal-content {
  max-height: 90vh;
  display: flex;
  flex-direction: column;
}

// 特殊处理宽度为80%的drawer（监控配置）
/deep/ .ant-drawer.ant-drawer-open .ant-drawer-content-wrapper {
  &[style*='width: 80%'] .ant-drawer-body {
    height: calc(100vh - 108px);
    overflow-y: auto;
    overflow-x: hidden;
  }
}

// 特殊处理宽度为70%的drawer（模型详情）
/deep/ .ant-drawer.ant-drawer-open .ant-drawer-content-wrapper {
  &[style*='width: 70%'] .ant-drawer-body {
    height: calc(100vh - 108px);
    overflow-y: auto;
    overflow-x: hidden;
  }
}
</style>
